/**
 * 
 */   
package com.gson.util;  

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


/**   
 * @作者 Stone
 * @创建日期 2014-6-20 上午9:33:59
 * @版本 V1.0
 * @类说明
 */
public class HttpUtil {

	/**
	 * @param httpUrl
	 * @return 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String getHttpResult(String httpUrl) throws Exception {
		String rtnXml = null;
		  
		//取得HttpClient对象  
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//HttpGet连接对象
		HttpGet httpRequest = new HttpGet(httpUrl);
		//返回对象
		CloseableHttpResponse response = null;
		// 设置请求和传输超时时间60s,设置cookie策略
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(60000).setConnectionRequestTimeout(60000)
				.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
		httpRequest.setConfig(requestConfig);
		
		//请求HttpClient，取得HttpResponse  
		response = httpClient.execute(httpRequest); 
			//请求成功  
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				//取得返回的字符串  
				rtnXml = EntityUtils.toString(response.getEntity()).trim(); 
			}
			return rtnXml;
	}

	/**
	 * UTF-8编码
	 * 
	 * @param source
	 * @return
	 */
	public static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 发送http请求取得返回的输入流
	 * 
	 * @param requestUrl 请求地址
	 * @return InputStream
	 */
	public static InputStream httpRequest(String requestUrl) {
		InputStream inputStream = null;
		try {

			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoInput(true);
			httpUrlConn.setRequestMethod("GET");
			
			httpUrlConn.connect();
			// 获得返回的输入流
			inputStream = httpUrlConn.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return inputStream;
	}

}
